package com.ssy.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ssy
 * <p>
 * 构造树形菜单
 */
public class TreeNodeBuilder {

    /**
     * 构造JSON数据树
     *
     * @param treeNodes 原始数据
     * @return
     */
    public static List<TreeNode> build(List<TreeNode> treeNodes, int topId) {
        //用于装一级菜单
        ArrayList<TreeNode> nodes = new ArrayList<>();
        for (TreeNode node : treeNodes) {
            if (node.getPid() == topId) {
                nodes.add(node);
                getChild(node, treeNodes);
            }
        }
        return nodes;
    }

    private static List<TreeNode> getChild(TreeNode node, List<TreeNode> treeNodes) {
        //用于装子菜单
        List<TreeNode> children = node.getChildren();
        if (children == null) {
            children = new ArrayList<TreeNode>();
            node.setChildren(children);
        }

        //循环所有的菜单
        for (TreeNode treeNode : treeNodes) {
            //获取当前循环的菜单的父ID
            Integer pid = treeNode.getPid();
            //将当前菜单的父ID 与 父菜单的ID 对比   如果相同则是 子菜单
            if (node.getId() .equals(pid) ) {
                children.add(treeNode);
                getChild(treeNode, treeNodes);
            }
        }
        return children;
    }

}
